import { onUnmounted, ref } from 'vue'

/**
 * @description 获取实时日期时间
 * @function useRealTime()
 * @return object = { year, month, day, hours, minutes, seconds }
 * @example
   <script setup lang="ts">
     const { year, month, day, hours, minutes, seconds } = useRealTime()
   </script>

   <template>
     <div>dateTime: {{ year }}年{{ month }}月{{ day }}日 {{ hours }}:{{ minutes }}:{{ seconds }}</div>
   </template>
 */
export const useRealTime = () => {
  const year = ref('')
  const month = ref('')
  const day = ref('')
  const hours = ref('')
  const minutes = ref('')
  const seconds = ref('')

  const timerId = ref(0)

  function getDateTime() {
    const { YY, MM, DD, HH, mm, ss } = formatDateTime()
    year.value = YY
    month.value = MM
    day.value = DD
    hours.value = HH
    minutes.value = mm
    seconds.value = ss

    timerId.value = window.requestAnimationFrame(getDateTime)
  }
  getDateTime()

  onUnmounted(() => {
    window.cancelAnimationFrame(timerId.value)
  })

  return {
    year,
    month,
    day,
    hours,
    minutes,
    seconds
  }
}

// 格式化日期时间
function formatDateTime() {
  const date = new Date()
  const obj: any = {
    YY: date.getFullYear(),
    MM: date.getMonth() + 1,
    DD: date.getDate(),
    HH: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds()
  }

  for (const key in obj) {
    obj[key] = String(obj[key]).padStart(2, '0')
  }

  return obj
}
